
var firstLoad = false;
var parentURL = "/";

$(document).ready(function() {
	statusflot.drawFlot("#placeholder", getSource(location.href));
	setTimeout(loadAnother, 200);
});

function loadAnother() {
	if (firstLoad) {
		statusflot.drawFlot("#placeholder-all", "*")
	} else {
		setTimeout(loadAnother, 200);
	}
}

var statusflot = {
	options: {
		lines: { show: true },
		points: { show: true },
		xaxis: { mode: "time", minTickSize: [1, "hour"],
		tickFormatter: function (val, axis) {
 			var d = new Date(val);
		    return d.format("dd/MM hh:mm");
		}},
		grid: { hoverable: true, clickable: true },
		autoHighlight: true
	},

	data: [],
	// fetch one series, adding to what we got
	alreadyFetched: {},

	drawFlot: function(target, source) {
		var placeholder = $(target);
		var flot = this;
		
		$.plot(placeholder, this.data, this.options);

		//var dataurl = "data-japan-gdp-growth.json";
		var previousPoint = null;
		$(target).bind("plothover", function (event, pos, item) {
			$("#x").text(pos.x.toFixed(2));
			$("#y").text(pos.y.toFixed(2));

			if ($("#enableTooltip:checked").length > 0) {
				if (item) {
					if (previousPoint != item.dataIndex) {
						previousPoint = item.dataIndex;
						
						$("#tooltip").remove();
						var time = new Date();
						time.setTime(parseInt(item.datapoint[0]));
						var x = time.format("yyyy-MM-dd hh:mm:ss"),
							y = item.datapoint[1].toFixed(2);
						
						showTooltip(item.pageX, item.pageY,
									item.series.label + " of " + x + " = " + y);
					}
				}
				else {
					$("#tooltip").remove();
					previousPoint = null;            
				}
			}
		});

		var dataurl = parentURL + "solr/select/?q=source%3A" + encodeURIComponent(source) + "&rows=0&facet=on&facet.date=fetchtime&facet.date=datetime&facet.date.start=NOW-1DAY/HOUR&facet.date.end=NOW%2B1DAY/HOUR&facet.date.gap=%2B1HOUR/HOUR&facet.date.other=all&wt=json";
        $.ajax({
            url: dataurl,
            method: 'GET',
            dataType: 'json',
            success: function(resData) {
				flot.pushSeries(source+"-Fetch", resData.facet_counts.facet_dates.fetchtime);
				flot.pushSeries(source, resData.facet_counts.facet_dates.datetime);
		        
				// and plot all we got
			    $.plot(placeholder, flot.data, flot.options);
				firstLoad = true;
			}
        });
	},
	
	pushSeries: function(label, list) {
		var series = { 
			"label": label,
			"data": []
		};
		for (var key in list) {
			if (key.match(/([^&]+)T([^&]+)Z/i)) {
				var timestamp = parseDate(key, "yyyy-MM-ddThh:mm:ssZ").getTime();
				series.data.push([timestamp, list[key]]);
			}
		}
        // let's add it to our current data
        if (!this.alreadyFetched[series.label]) {
            this.alreadyFetched[series.label] = true;
            this.data.push(series);
        }
	}
};

/*
		// then fetch the data with jQuery
		onDataReceived: function(resData) {
			pushSeries(source+"-Fetch", resData.facet_counts.facet_dates.fetchtime);
			pushSeries(source, resData.facet_counts.facet_dates.datetime);
            
            // and plot all we got
            $.plot(placeholder, data, options);
	     },

	$("#placeholder").bind("plothover", function (event, pos, item) {
        //alert("You clicked at " + pos.x + ", " + pos.y);
        // axis coordinates for other axes, if present, are in pos.x2, pos.x3, ...
        // if you need global screen coordinates, they are pos.pageX, pos.pageY
 
        if (item) {
          //highlight(item.series, item.datapoint);
		  var time = new Date();
		  time.setTime(parseInt(item.datapoint[0]));
          alert(time + " " + item.datapoint[1]);
        }
	});*/
